﻿using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
using ZXthex;

public class Demo : MonoBehaviour
{
    const int kMaxLogCount = 1000;

    static readonly string[] splitStrings = new string[] { "\n" };

#pragma warning disable CS0649 

    [SerializeField] Text logText;

    [SerializeField] InputField inf;

#pragma warning restore

    Queue<string> logs;

    List<string> historyInput;
    int indexOfHistory;

    StringBuilder strB;
    private void Awake()
    {
        logs = new Queue<string>(kMaxLogCount);
        historyInput = new List<string>(kMaxLogCount / 2);
        strB = new StringBuilder(kMaxLogCount * 10);
    }

    private void Start()
    {
        MiniCSharpExecuter.DefineMacro("SceneManager", "UnityEngine.SceneManagement.SceneManager");
    }

    public void ExecuteString()
    {
        if (!inf.text.Contains("\n"))
            return;


        var text = inf.text.Replace("\r", "");
        inf.text = "";

        EnqueueLog(text.TrimEnd('\n'));

        var texts = text.Split(splitStrings, System.StringSplitOptions.RemoveEmptyEntries);
        for (int i = 0; i < texts.Length; i++)
        {
            var result = MiniCSharpExecuter.Execute(texts[i]);
            EnqueueLog("<i><color=#3f3f3f> " + result + "</color></i>");
            HistoryAdd(texts[i]);
        }
    }

    void EnqueueLog(string log)
    {
        logs.Enqueue(log);
        if (logs.Count > kMaxLogCount - 1)
        {
            logs.Dequeue();
        }

        strB.Length = 0;
        foreach (var line in logs)
        {
            strB.Append(line);
            strB.Append('\n');
        }
        logText.text = strB.ToString();
    }

    void HistoryAdd(string line)
    {
        historyInput.Add(line);
        indexOfHistory = historyInput.Count;
    }

    private void Update()
    {
        if (Input.GetKeyUp(KeyCode.UpArrow))
        {
            if (indexOfHistory > 0)
            {
                indexOfHistory--;
                inf.text = historyInput[indexOfHistory];
                inf.caretPosition = inf.text.Length + 1;
            }
        }
        if (Input.GetKeyDown(KeyCode.DownArrow))
        {
            if (indexOfHistory < historyInput.Count - 1)
            {
                indexOfHistory++;
                inf.text = historyInput[indexOfHistory];
                inf.caretPosition = inf.text.Length + 1;
            }
        }
    }
}
